//
//  HomeViewController.m
//  PlayCatchGame
//
//  Created by sugar chestnut on 2018/1/15.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "HomeViewController.h"
#import "AppHeader.h"
#import "HomeHeaderView.h"
#import "HomeSectionView.h"
#import "HomeItemCell.h"

#import "HomeSingInView.h"
#import "PacketAlertView.h"

#import "SignInViewController.h"
#import "MyAssetInfoVC.h"
#import "GameCentreVC.h"
#import "HomeAdPictureModel.h"
#import "GoodsModel.h"
#import "HomeSectionContainer.h"

@interface HomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    // item之间的间距
    CGFloat spaceItem;
    // 每行几个
    NSInteger rowItem;
    // 表头高度
    CGFloat collectionHeaderHeight;
    // 分页，当前页
    NSInteger currentPage;
    // 是否第一次进入该页面
    BOOL isFirstIntoThisPage;
    
    
}

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) UIButton *navRightButton;
@property (strong, nonatomic) HomeHeaderView *collectionHeaderView;

@property (nonatomic, strong) NSMutableArray<HomeSectionContainer *> *goodsList;

@property (nonatomic, strong) NSMutableArray *headerImgUrls;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    spaceItem =10.0;
    rowItem =2;
    collectionHeaderHeight =240.0;
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeItemCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"HomeItemCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"HomeSectionView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionView"];
//    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionView"];
    self.collectionView.contentInset = UIEdgeInsetsMake(collectionHeaderHeight, 0, 0, 0);
    self.collectionHeaderView =[[[NSBundle mainBundle] loadNibNamed:@"HomeHeaderView" owner:nil options:nil] lastObject];
    [self.collectionHeaderView didPageViewBlock:^(SDCycleScrollView *cycleScrollView, NSInteger index) {
        
        if (self.headerImgUrls.count > index) {
            
            AXWebViewController *vc = [[AXWebViewController alloc] initWithURL:[NSURL URLWithString:self.headerImgUrls[index]]];
            [self.navigationController pushViewController:vc animated:YES];
        }
    
    }];
    [self.view addSubview:self.collectionHeaderView];
    
    [self showNavigatioBarSeat:BaseBarItemDirectionLeft withImage:[UIImage imageNamed:@"qiandao"]];
    [self.navRightButton addTarget:self action:@selector(navRightItemClick:) forControlEvents:UIControlEventTouchUpInside];
    
    // 上拉，下拉 刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 1;
        [self _selectAllGoodsShowingHud:NO];
        if (self.collectionView.mj_footer.state != MJRefreshStateIdle) {
            self.collectionView.mj_footer.state = MJRefreshStateIdle;
        }
    }];
    self.collectionView.mj_header.ignoredScrollViewContentInsetTop = self.collectionHeaderView.xl_height-50;
    
    self.collectionView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self _selectAllGoodsShowingHud:YES];
    }];
    
    /// 零时写的 看效果
//    [TimerHandler performAfterDelay:5 handler:^{
//        [self showSinginAlertView];
//    }];
#warning ------------签到------------
//    [self _queryUserIsSign];
    
    [self.collectionView.mj_header beginRefreshing];
    [self _adPicture];
    
    isFirstIntoThisPage = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.collectionView.indexPathsForVisibleItems.count > 0) {
        
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:(UICollectionViewScrollPositionNone) animated:NO];
    }
//    [self.collectionView.mj_header beginRefreshing];
    
    if (isFirstIntoThisPage) {
        isFirstIntoThisPage = NO;
    } else {
        currentPage = 1;
        [self _selectAllGoodsShowingHud:NO];
        if (self.collectionView.mj_footer.state != MJRefreshStateIdle) {
            
            self.collectionView.mj_footer.state = MJRefreshStateIdle;
        }
    }
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.collectionHeaderView.frame =CGRectMake(10, 0, KScreenWidth-20, collectionHeaderHeight);
    });
}

#pragma mark - Request Network

- (void)_selectAllGoodsShowingHud:(BOOL)isShowHud {
    [HttpUrl NetErrorGET:@"goods/selectAllGoods" dict:@{@"current":@(currentPage)} hud:self.view isShow:isShowHud WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            NSArray *arr = data[@"data"];
            if (currentPage == 1) {
                [self.goodsList removeAllObjects];
            }
            if (arr.count == 0) {
                if ([self.collectionView.mj_footer isRefreshing]) {
                    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                for (NSDictionary *sectionDic in arr) {
                    HomeSectionContainer *container = [[HomeSectionContainer alloc] init];
                    container.title = sectionDic[@"title"];
                    for (NSDictionary *dic in sectionDic[@"content"]) {
                        GoodsModel *goodsModel = [GoodsModel mj_objectWithKeyValues:dic];
                        [container.contentList addObject:goodsModel];
                    }
                    [self.goodsList addObject:container];
                }
                [self.collectionView reloadData];
            }
            [self.collectionView.mj_header endRefreshing];

            
        } else {
            ShowAlertTitle(data[@"msg"]);
            [self.collectionView.mj_header endRefreshing];
            [self.collectionView.mj_footer endRefreshing];
        }
    } WithFailBlock:^(id data) {
        ShowAlertTitle(@"网络连接错误");
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}


// 首页轮播图
- (void)_adPicture {
    [HttpUrl GET:@"eachPicture/appSelectAll" dict:nil hud:self.view isShow:NO WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            NSMutableArray *arr = [NSMutableArray array];

            for (NSDictionary *dic in data[@"data"]) {
                [arr addObject:dic[@"imgUrl"]];
                [self.headerImgUrls addObject:dic[@"linkUrl"]];
            }
            self.collectionHeaderView.carouselScrollImage.imageURLStringsGroup = arr;
        } else {
            ShowAlertTitle(data[@"msg"]);
        }
    }];
}

- (void)_queryUserIsSign {
    [HttpUrl POST:@"signRecord/confirmSignRecord" dict:nil hud:self.view isShow:NO WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            [TimerHandler performAfterDelay:1 handler:^{
                [self showSinginAlertView];
            }];
        } else {
            ShowAlertTitle(data[@"msg"]);
        }
    }];
    
}


#pragma mark - Event Response
- (UIButton *)navRightButton {
    if (!_navRightButton) {
        _navRightButton =[UIButton buttonWithType:UIButtonTypeCustom];
        _navRightButton.frame = CGRectMake(0, 0, KScreenWidth/5, 30);
        _navRightButton.backgroundColor =[UIColor whiteColor];
        _navRightButton.cornerRadius =14;
        [_navRightButton setAttributedTitle:[HomeViewController rightBtnAttributedString:@" 0 +"] forState:UIControlStateNormal];
        [_navRightButton setImage:[UIImage imageNamed:@"jindou-2"] forState:UIControlStateNormal];
        _navRightButton.titleLabel.font =[UIFont systemFontOfSize:16];
        [_navRightButton setTitleColor:[UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:1.00] forState:UIControlStateNormal];
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:_navRightButton];
        self.navigationItem.rightBarButtonItem =item;
    }
   return _navRightButton;
}

/// 导航右边按钮
- (void)navRightItemClick:(UIButton*)button {
    [MyAssetInfoVC rechargeAlertView_rechargeRusult:^(NSInteger type) {
        NSLog(@"type=%ld", type);
    }];
}

- (void)barItemLeftButtonClick:(UIButton*)button {
    SignInViewController *singInVC =[[SignInViewController alloc]init];
    singInVC.hidesBottomBarWhenPushed =YES;
    singInVC.title =@"签到";
    [self.navigationController pushViewController:singInVC animated:YES];
}



+ (NSMutableAttributedString *)rightBtnAttributedString:(NSString *)title {
    NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc]initWithString:title];
    if ([title containsString:@"+"]) {
        NSRange range =[title rangeOfString:@"+"];
        [attributedString setAttributes:@{NSForegroundColorAttributeName:APP_DEFAULT_COLOUR} range:range];
    }
    return attributedString;
}


//有几个区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.goodsList.count;
}

//每个区有几个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.goodsList[section].contentList.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat itemWidth =(KScreenWidth-(rowItem+1)*spaceItem)/(rowItem*1.0);
    
    return CGSizeMake(itemWidth, itemWidth*1.3);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(spaceItem, spaceItem, spaceItem, spaceItem);
}


//重用cell
#pragma mark CollectionSelfCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomeItemCell" forIndexPath:indexPath];
    cell.cornerRadius =5;
    cell.backgroundColor =[UIColor whiteColor];
    GoodsModel *model = self.goodsList[indexPath.section].contentList[indexPath.row];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.coverUrl]];
    cell.titleLabel.text = model.goodsTitle;
    [cell.subTitle setTitle:[NSString stringWithFormat:@"%ld/次", model.goldPrice] forState:UIControlStateNormal];
    return cell;
}

//返回每个分区的页眉和页脚 -- 页眉和页脚也可以重用

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    HomeSectionView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeSectionView" forIndexPath:indexPath];
//    headerView.backgroundColor =[UIColor clearColor];
    
//    HomeSectionView *sectionView =[HomeSectionView loadNib:@"HomeSectionView" frame:CGRectMake(10, 0, KScreenWidth-(spaceItem*2), CGRectGetHeight(headerView.frame))];
    HomeSectionContainer *container = self.goodsList[indexPath.section];
    headerView.titleLabel.text = [NSString stringWithFormat:@"%@", container.title];
//    [headerView addSubview:sectionView];
    
    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(KScreenWidth, 35);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    /// 零时写的 看效果
    if (indexPath.section ==1) {
        [self showAwardsAlertView:  1];
    } else if (indexPath.section ==2) {
        [self showAwardsAlertView:2];
    } else {
        GameCentreVC *gameVC =[[GameCentreVC alloc]init];
        gameVC.hidesBottomBarWhenPushed =YES;
        [self.navigationController pushViewController:gameVC animated:YES];
    }
    /**  请求示例
    [RequestManager postRequestURL:@"请求完整地址" parameter:@{@"key":@"value"} withBlock:^(id object, NSError *error) {
        if (object) {
            if (Request_Success) {
                NSLog(@"Request=%@", object);
                newBlock(1);
            } else {
                ShowAlertTitle(object[@"msg"]);
                newBlock(-1);
            }
        } else {
            newBlock(-1);
            ShowAlertTitle(@"服务器或网络错误,请稍后再试");
        }
    }];
     */
}

/// 自定义区头跟着滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat height =CGRectGetHeight(self.collectionHeaderView.frame);
    self.collectionHeaderView.frame =CGRectMake(10, -(scrollView.contentOffset.y+height), CGRectGetWidth(self.collectionHeaderView.frame), height);
}

#pragma mark - Private Method
/// 签到弹框
- (void)showSinginAlertView {
    AlertBgView *alertView =[[AlertBgView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) clickRemove:YES bgColor:[UIColor colorWithWhite:0 alpha:0.6]];
    [alertView showView];
    alertView.centerView_height.constant =400;
    
    CGFloat width =300;
    HomeSingInView *homeView =[HomeSingInView loadNib:@"HomeSingInView" frame:CGRectZero];
    homeView.viewFrame =CGRectMake((KScreenWidth-width)/2.0, 0, width, 400);
    homeView.cornerRadius =8.0;
    [alertView.centerView addSubview:homeView];
    [homeView viewButtonClickBlock:^(UIButton *button) {
        if (button ==homeView.closeButton) {
            [homeView removeFromSuperview];
            [alertView removeFromSuperview];
        } else if (button ==homeView.singinButton) {
            NSLog(@"点击签到");
        }
    }];
}
/// 红包弹框 (1:注册红包 2:领取注册红包)
- (void)showAwardsAlertView:(NSInteger)type {
    AlertBgView *alertView =[[AlertBgView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight) clickRemove:NO bgColor:[UIColor colorWithWhite:0 alpha:0.6]];
    [alertView showView];
    alertView.centerView_height.constant =450;
    
    CGFloat width =320;
    PacketAlertView *packetView =[PacketAlertView loadNib:@"PacketAlertView" frame:CGRectMake((KScreenWidth-width)/2.0, 0, width, 450)];
    packetView.cornerRadius =8.0;
    packetView.packetType =type;
    if (type ==1) {
        packetView.titleString =@"娃娃机送您一个\n红包";
    } else if (type ==2) {
        packetView.titleString =@"80金豆\n恭喜您获得";
    }
    [alertView.centerView addSubview:packetView];
    [packetView viewButtonClickBlock:^(UIButton *button) {
        if (button ==packetView.closeButton) {
            [packetView removeFromSuperview];
            [alertView removeFromSuperview];
        } else if (button ==packetView.bottomBtn) {
            NSLog(@"点击红包");
        }
    }];
}

#pragma mark - Property Override

- (NSMutableArray<HomeSectionContainer *> *)goodsList {
    if (_goodsList == nil) {
        _goodsList = [[NSMutableArray alloc] init];
    }
    return _goodsList;
}

- (NSMutableArray *)headerImgUrls {
    if (_headerImgUrls == nil) {
        _headerImgUrls = [NSMutableArray array];
    }
    return _headerImgUrls;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

